var createError = require('http-errors');
// 导入 express 模块
const express = require('express')
// 创建 express 的服务器实例
const app = express()
//导入path
const path = require('path');
//导入cookie
const cookieParser = require("cookie-parser")
//导入session
const session = require("express-session")
//导入morgan日志记录
const logger = require("morgan");

// 导入并注册web路由模块
const webRouter = require('./routers/web')
// 导入并注册admin路由模块
const adminRouter = require('./routers/admin')

//托管静态文件
app.use(express.static("public"));

//设置session参数
app.use(
  session({
    secret: "keyboard cat", // 对session id 相关的cookie 进行签名
    resave: false,
    saveUninitialized: true, // 是否保存未初始化的会话
    cookie: { maxAge: 1000 * 60 * 60 * 24 }, // 设置 session 的有效时间，单位毫秒},
  })
);

app.use(express.json());
app.use(express.urlencoded({ extended: false }))


app.use(cookieParser())
app.use(logger('dev'));

//路由控制器
app.use(webRouter)
app.use(adminRouter)
//设置public文件夹为存放静态文件的目录
app.use(express.static(path.join(__dirname, 'public')));

//处理跨域问题
app.all("*", function(req, res, next) {
  if (!req.get("Origin")) return next();
  // use "*" here to accept any origin
  res.set("Access-Control-Allow-Origin","*");
  res.set("Access-Control-Allow-Methods", "GET");
  res.set("Access-Control-Allow-Headers", "X-Requested-With,Origin,Content-Type,Accept");
  // res.set('Access-Control-Allow-Max-Age', 3600);
  if ("OPTIONS" === req.method) return res.sendStatus(200);
  next();
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// 调用 app.listen 方法，指定端口号并启动web服务器
app.listen(3000, function () {
  console.log('api server running at http://127.0.0.1:3000')
})

